import sys
from pathlib import Path

from loguru import logger
from motor.motor_asyncio import AsyncIOMotorClient
from redis.asyncio import Redis
from redis.asyncio.connection import ConnectionPool

from .config import config


class Dependencies:
    """
    提供基础的第三方依赖组件，如数据库连接、缓存、日志等。
    """

    @classmethod
    async def init_redis_pool(cls):
        """
        初始化redis连接池
        :return:
        """
        cls.redis_pool = ConnectionPool.from_url(config.redis.url, max_connections=config.redis.maxsize)
        cls.redis_client = Redis(connection_pool=cls.redis_pool)

    @classmethod
    async def get_redis(cls)->Redis:
        """
        提供redis连接
        :return: redis 链接
        """
        if not hasattr(cls, 'redis_client'):
            await cls.init_redis_pool()
        return cls.redis_client

    @classmethod
    async def init_mongo(cls):
        """
        初始化mongo连接池
        :return:
        """
        cls.mongo_client = AsyncIOMotorClient(
            config.mongodb.url,
            maxPoolSize=config.mongodb.maxsize,
            minPoolSize=config.mongodb.minsize,
            # maxIdleTimeMS=getattr(config.mongodb, 'maxidletimems', None)
        )
        # 默认链接配置的数据库
        cls.mongo_db = cls.mongo_client.get_database()

    @classmethod
    def get_mongo(cls,db_name: str = None):
        """
        提供mongo连接
        :return:
        """
        if not hasattr(cls, 'mongo_db'):
            cls.init_mongo()
        if db_name:
            return cls.mongo_client[db_name]
        return cls.mongo_db

    @classmethod
    def init_logger(cls):
        """
        提供日志组件
        :return:
        """
        log_path = Path(config.logging.dir)
        log_path.mkdir(parents=True, exist_ok=True)
        # 日志格式
        log_format = (
            "<green>{time:YYYY-MM-DD HH:mm:ss.SSS}</green> | "
            "<level>{level: <8}</level> | "
            "<cyan>{name}</cyan>:<cyan>{function}</cyan>:<cyan>{line}</cyan> - "
            "<level>{message}</level>"
        )
        logger.remove()
        logger.add(
            sys.stdout,
            format=log_format,
            level=config.logging.level,
            enqueue=True
        )

        logger.add(
            log_path / "app_{time:YYYY-MM-DD}.log",
            rotation="00:00",  # 每天零点创建新文件
            retention="30 days",  # 保留30天的日志
            format=log_format,
            level=config.logging.level,
            encoding="utf-8",
            enqueue=True
        )
        cls.logger = logger

    @classmethod
    def get_logger(cls):
        """
        提供日志组件
        :return:
        """
        if not hasattr(cls,'logger'):
            cls.init_logger()
        return cls.logger